<template>
  <div>
    <div class="user-tools">
      <el-button type="primary" @click="addUserHandle" icon="el-icon-plus">新增用户</el-button>
      <el-button
        v-if="isShowDelete"
        type="success"
        icon="el-icon-upload2"
        @click="exportUserExcelHandle"
      >
        导出选用的用户
      </el-button>
      <el-button
        v-if="isShowDelete"
        type="danger"
        icon="el-icon-delete"
        @click="deleteAllUserHandle"
      >
        选中删除用户
      </el-button>
    </div>
  </div>
</template>

<script>
import { utils, writeFile } from 'xlsx'
import { exportUserData } from '@/utils/tools'
export default {
  props: ['selectUserIds', 'deleteAllUser', 'tableData'],
  methods: {
    // 导出用户为excel文件
    async exportUserExcelHandle() {
      const loading = this.$loading({
        lock: true,
        text: '玩命生成文件中，请稍等！',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        // 把json数据导入为excel中的sheet数据类型
        //  const sheet = utils.json_to_sheet([
        //   { 姓名: '张三', 性别: '男', 年龄: '18' },
        //   { 姓名: '李四', 性别: '女', 年龄: '19' },
        //   { 姓名: '王五', 性别: '男', 年龄: '20' }
        // ])
        const sheet = utils.json_to_sheet(exportUserData(this.tableData))
        // 创建工作簿
        const workerBook = utils.book_new()
        utils.book_append_sheet(workerBook, sheet, '用户信息记录')
        // 将工作簿数据写入或下载到文件
        writeFile(workerBook, '用户信息记录.xlsx')
        this.$message({
          type: 'success',
          duration: 3000,
          message: '导出用户成功',
          onClose: () => {
            loading.close()
          }
        })
      } catch (error) {
        this.$message({
          type: 'error',
          duration: 3000,
          message: '导出失败',
          onClose: () => {
            loading.close()
          }
        })
      }
    },
    addUserHandle() {
      this.$emit('addUserHandle', true)
    },
    async deleteAllUserHandle() {
      // 确认框
      try {
        await this.$confirm('此操作将永久删除该选中用户, 是否继续?', '提示', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消删除',
          type: 'warning'
        })
        await this.$message({
          type: 'success',
          duration: 3000,
          message: '删除用户成功',
          onClose: () => {
            this.deleteAllUser(this.selectUserIds)
          }
        })
      } catch (error) {}
    }
  },
  computed: {
    isShowDelete() {
      return this.selectUserIds.length > 0
    }
  }
}
</script>

<style lang="scss" scoped>
.user-tools {
  background: #fff;
  padding: 10px;
  margin-top: 5px;
}
</style>
